/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on 2011/12/29, 上午 09:43:12
 */
package elaborate.tag_analysis.client;

import elaborate.tag_analysis.client.actions.*;
import elaborate.tag_analysis.client.applications.Application;
import elaborate.tag_analysis.client.applications.ApplicationConfiguration;
import elaborate.tag_analysis.client.applications.ApplicationConfigurations;
import elaborate.tag_analysis.client.applications.ApplicationContext;
import elaborate.tag_analysis.client.applications.DefaultApplicationContextImpl;
import elaborate.tag_analysis.client.event.TagProcessingEvent;
import elaborate.tag_analysis.client.event.TagProcessingEventListener;
import elaborate.tag_analysis.client.ui.ResourceTreeRenderer;
import elaborate.tag_analysis.client.ui.model.OndemandResourceTreeModel;
import elaborate.tag_analysis.client.ui.model.ResourceTreeNode;
import elaborate.tag_analysis.client.utils.TableUtil;
import elaborate.task.DefaultTaskQueueFactory;
import elaborate.task.Task;
import elaborate.task.TaskQueue;
import elaborate.task.TaskQueueEvent;
import elaborate.task.TaskQueueEventAdapter;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.TreePath;
import org.springframework.context.support.FileSystemXmlApplicationContext;

/**
 *
 * @author lendle
 */
public final class MainFrame extends javax.swing.JFrame implements TagProcessingEventListener {

    private TaskQueue taskQueue = null;
    private ApplicationContext context = null;
    private DefaultServiceContextImpl serviceContext = null;
    private org.springframework.context.ApplicationContext appConfs = null;
    private JMenuItem lastActivatedApplicationMenuItem=null;
    
    //ActionHandlers
    private GenerateCharacteristicVectorActionHandler generateCharacteristicVectorActionHandler=new GenerateCharacteristicVectorActionHandler();
    private GenerateCossimCSVActionHandler generateCossimCSVActionHandler=new GenerateCossimCSVActionHandler();
    private GenerateResourceListActionHandler generateResourceListActionHandler=new GenerateResourceListActionHandler();
    private GenerateConnectedClustersActionHandler generateConnectedClustersActionHandler=new GenerateConnectedClustersActionHandler();
    private CalculateClosenessCentralityActionHandler calculateClosenessCentralityActionHandler=new CalculateClosenessCentralityActionHandler();
    //////////////////////////////////////////////////////////////////

    /** Creates new form MainFrame */
    public MainFrame() {
        initComponents();
        this.taskQueue = new DefaultTaskQueueFactory().newTaskQueue();
        this.taskQueue.addTaskQueueListener(new TaskQueueEventAdapter() {

            @Override
            public void taskAdded(TaskQueueEvent e) {
                MainFrame.this.loadingProgressBar1.start();
            }

            @Override
            public void taskQueueEmptied(TaskQueueEvent e) {
                MainFrame.this.loadingProgressBar1.stop();
            }
        });
        this.taskQueue.start();
        this.context = new DefaultApplicationContextImpl(this.taskQueue);
        this.context.addTagProcessingEventListener(this);
        initServiceContext();
        ((DefaultApplicationContextImpl)this.context).setServiceContext(serviceContext);
        
        //initialize ActionHandler instances
        generateCharacteristicVectorActionHandler.init(serviceContext);
        generateCossimCSVActionHandler.init(serviceContext);
        generateResourceListActionHandler.init(serviceContext);
        generateConnectedClustersActionHandler.init(serviceContext);
        calculateClosenessCentralityActionHandler.init(serviceContext);
        ////////////////////////////////////

        ResourceTreeRenderer resourceTreeRenderer = new ResourceTreeRenderer();
        resourceTreeRenderer.setServiceContext(serviceContext);

        try {
            OndemandResourceTreeModel treeModel = new OndemandResourceTreeModel();
            treeModel.setServiceContext(serviceContext);
            treeResources.setModel(treeModel);
            treeModel.getRootNode().setChildrenLoaded(true);
            treeModel.getRootNode().setAlt("Root");
            this.treeResources.setCellRenderer(resourceTreeRenderer);

            ImageIcon icon = new ImageIcon(this.getClass().getClassLoader().getResource("exe_icon.PNG"));
            this.setIconImage(icon.getImage());
            try {
                this.configureApplications();
            } catch (Exception ex) {
                Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void initServiceContext() {
        this.serviceContext = new DefaultServiceContextImpl();
        this.serviceContext.setTagTable(tableTags);
        this.serviceContext.setResourceTree(treeResources);
        this.serviceContext.setTaskQueue(taskQueue);
        this.serviceContext.setMainFrame(this);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jSplitPane1 = new javax.swing.JSplitPane();
        mainPanel = new javax.swing.JPanel();
        jSplitPane2 = new javax.swing.JSplitPane();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableTags = new javax.swing.JTable();
        jPanel5 = new javax.swing.JPanel();
        btSave = new javax.swing.JButton();
        buttonDeleteTag = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        btReloadResources = new javax.swing.JButton();
        scrollPane = new javax.swing.JScrollPane();
        treeResources = new javax.swing.JTree();
        statusPanel = new javax.swing.JPanel();
        loadingProgressBar1 = new elaborate.task.ui.LoadingProgressBar();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        mnuItemLoadCategory = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();
        jMenu3 = new javax.swing.JMenu();
        menuItemGenerateResourceList = new javax.swing.JMenuItem();
        menuItemCharacteristicVector = new javax.swing.JMenuItem();
        menuItemCossimCSV = new javax.swing.JMenuItem();
        menuItemConnectedClusters = new javax.swing.JMenuItem();
        menuItemClosenessCentrality = new javax.swing.JMenuItem();
        menuApplications = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Tag Analysis Tool");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel1.setLayout(new java.awt.BorderLayout());

        jSplitPane1.setDividerLocation(250);
        jSplitPane1.setOneTouchExpandable(true);

        mainPanel.setLayout(new java.awt.BorderLayout());
        jSplitPane1.setRightComponent(mainPanel);

        jSplitPane2.setDividerLocation(400);
        jSplitPane2.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
        jSplitPane2.setOneTouchExpandable(true);

        jPanel2.setLayout(new java.awt.BorderLayout());

        tableTags.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Tag"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(tableTags);

        jPanel2.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        btSave.setText("Save");
        btSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSaveActionPerformed(evt);
            }
        });
        jPanel5.add(btSave);

        buttonDeleteTag.setText("Delete");
        buttonDeleteTag.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonDeleteTagActionPerformed(evt);
            }
        });
        jPanel5.add(buttonDeleteTag);

        jPanel2.add(jPanel5, java.awt.BorderLayout.SOUTH);

        jSplitPane2.setBottomComponent(jPanel2);

        jPanel3.setLayout(new java.awt.BorderLayout());

        btReloadResources.setText("Reload");
        jPanel4.add(btReloadResources);

        jPanel3.add(jPanel4, java.awt.BorderLayout.SOUTH);

        treeResources.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                treeResourcesMouseClicked(evt);
            }
        });
        scrollPane.setViewportView(treeResources);

        jPanel3.add(scrollPane, java.awt.BorderLayout.CENTER);

        jSplitPane2.setLeftComponent(jPanel3);

        jSplitPane1.setLeftComponent(jSplitPane2);

        jPanel1.add(jSplitPane1, java.awt.BorderLayout.CENTER);

        statusPanel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        statusPanel.setLayout(new java.awt.BorderLayout());
        statusPanel.add(loadingProgressBar1, java.awt.BorderLayout.EAST);

        jPanel1.add(statusPanel, java.awt.BorderLayout.SOUTH);

        jMenu1.setText("File");

        mnuItemLoadCategory.setText("Load Category");
        jMenu1.add(mnuItemLoadCategory);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Analysis");

        jMenu3.setText("Cosine Similarity");

        menuItemGenerateResourceList.setText("Generate Resource List");
        menuItemGenerateResourceList.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemGenerateResourceListActionPerformed(evt);
            }
        });
        jMenu3.add(menuItemGenerateResourceList);

        menuItemCharacteristicVector.setText("Generate Characteristic Vectors");
        menuItemCharacteristicVector.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemCharacteristicVectorActionPerformed(evt);
            }
        });
        jMenu3.add(menuItemCharacteristicVector);

        menuItemCossimCSV.setText("Generate Cossim CSV");
        menuItemCossimCSV.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemCossimCSVActionPerformed(evt);
            }
        });
        jMenu3.add(menuItemCossimCSV);

        menuItemConnectedClusters.setText("Generate Connected Clusters");
        menuItemConnectedClusters.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemConnectedClustersActionPerformed(evt);
            }
        });
        jMenu3.add(menuItemConnectedClusters);

        menuItemClosenessCentrality.setText("Calculate Closeness Centrality");
        menuItemClosenessCentrality.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                menuItemClosenessCentralityActionPerformed(evt);
            }
        });
        jMenu3.add(menuItemClosenessCentrality);

        jMenu2.add(jMenu3);

        jMenuBar1.add(jMenu2);

        menuApplications.setText("Application");
        jMenuBar1.add(menuApplications);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 800, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void treeResourcesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_treeResourcesMouseClicked
        // TODO add your handling code here:
        if (evt.getClickCount() == 2 && evt.getButton() == MouseEvent.BUTTON1) {
            //only process double click of left button
            int row = this.treeResources.getRowForLocation(evt.getX(), evt.getY());
            final TreePath path = this.treeResources.getPathForRow(row);
            if (path == null) {
                return;
            }
            final ResourceTreeNode resourceNode = (ResourceTreeNode) path.getLastPathComponent();
            if(resourceNode==null || resourceNode.isCategory()){
                return;
            }
            this.taskQueue.addTask(new Task() {

                @Override
                public Object run() throws Exception {
                    TableUtil.clearJTableWithDefaultModel(tableTags);
                    
                    serviceContext.getActiveApplication().requestTags4Resource(resourceNode.getResource().getName());
                    //System.out.println(resourceNode.getResource().getName());
                    return null;
                }
            }, true);

        }
    }//GEN-LAST:event_treeResourcesMouseClicked

    private void buttonDeleteTagActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonDeleteTagActionPerformed
        // TODO add your handling code here:
        int row = this.tableTags.getSelectedRow();
        if (row != -1) {
            DefaultTableModel model = (DefaultTableModel) this.tableTags.getModel();
            model.removeRow(row);
            SwingUtilities.invokeLater(new Runnable() {

                @Override
                public void run() {
                    tableTags.updateUI();
                }
            });
        }
    }//GEN-LAST:event_buttonDeleteTagActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        serviceContext.getActiveApplication().closing();
    }//GEN-LAST:event_formWindowClosing

    private void btSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSaveActionPerformed
        // TODO add your handling code here:
        this.taskQueue.addTask(new Task() {

            @Override
            public Object run() throws Exception {
                ResourceTreeNode workingNode = (ResourceTreeNode) treeResources.getSelectionPath().getLastPathComponent();
                ResourceTreeNode categoryNode = (ResourceTreeNode) treeResources.getSelectionPath().getParentPath().getLastPathComponent();
                DefaultTableModel model = (DefaultTableModel) tableTags.getModel();
                List<TagEntry> entries = new ArrayList<TagEntry>();
                for (int i = 0; i < model.getRowCount(); i++) {
                    entries.add(new TagEntry(model.getValueAt(i, 0).toString()));
                }
                if (serviceContext.getActiveApplication() != null) {
                    serviceContext.getActiveApplication().getResourceHandler().saveTags(entries, workingNode, categoryNode);
                }
                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        treeResources.repaint();
                    }
                });
                return null;
            }
        });
    }//GEN-LAST:event_btSaveActionPerformed

    private void menuItemCharacteristicVectorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemCharacteristicVectorActionPerformed
        // TODO add your handling code here:
        this.generateCharacteristicVectorActionHandler.handle(evt);
    }//GEN-LAST:event_menuItemCharacteristicVectorActionPerformed

    private void menuItemCossimCSVActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemCossimCSVActionPerformed
        // TODO add your handling code here:
        this.generateCossimCSVActionHandler.handle(evt);
    }//GEN-LAST:event_menuItemCossimCSVActionPerformed

    private void menuItemGenerateResourceListActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemGenerateResourceListActionPerformed
        // TODO add your handling code here:
        this.generateResourceListActionHandler.handle(evt);
    }//GEN-LAST:event_menuItemGenerateResourceListActionPerformed

    private void menuItemConnectedClustersActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemConnectedClustersActionPerformed
        // TODO add your handling code here:
        this.generateConnectedClustersActionHandler.handle(evt);
    }//GEN-LAST:event_menuItemConnectedClustersActionPerformed

    private void menuItemClosenessCentralityActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuItemClosenessCentralityActionPerformed
        // TODO add your handling code here:
        this.calculateClosenessCentralityActionHandler.handle(evt);
    }//GEN-LAST:event_menuItemClosenessCentralityActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new MainFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btReloadResources;
    private javax.swing.JButton btSave;
    private javax.swing.JButton buttonDeleteTag;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JSplitPane jSplitPane2;
    private elaborate.task.ui.LoadingProgressBar loadingProgressBar1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JMenu menuApplications;
    private javax.swing.JMenuItem menuItemCharacteristicVector;
    private javax.swing.JMenuItem menuItemClosenessCentrality;
    private javax.swing.JMenuItem menuItemConnectedClusters;
    private javax.swing.JMenuItem menuItemCossimCSV;
    private javax.swing.JMenuItem menuItemGenerateResourceList;
    private javax.swing.JMenuItem mnuItemLoadCategory;
    private javax.swing.JScrollPane scrollPane;
    private javax.swing.JPanel statusPanel;
    private javax.swing.JTable tableTags;
    private javax.swing.JTree treeResources;
    // End of variables declaration//GEN-END:variables

    @Override
    public void tagExtracted(TagProcessingEvent event) {
        DefaultTableModel model = (DefaultTableModel) this.tableTags.getModel();
        for (TagEntry tag : event.getTagEntries()) {
            model.addRow(new Object[]{tag.getName()});
        }
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                tableTags.updateUI();
            }
        });
    }

    private void configureApplications() throws Exception {
        appConfs = new FileSystemXmlApplicationContext(new File("applications.xml").getAbsolutePath());
        //System.out.println( ((ApplicationConfigurations)appConfs.getBean("applications")).getConfigurations().get(0).getInstance());
        List<ApplicationConfiguration> confs = ((ApplicationConfigurations) appConfs.getBean("applications")).getConfigurations();
        for (ApplicationConfiguration conf : confs) {
            final Application app = conf.getInstance();
            app.init(context);
            final JMenuItem menuItem = menuApplications.add(conf.getDisplayName());
            menuItem.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent ae) {
                    try {
                        //activate the application
                        if(lastActivatedApplicationMenuItem!=null){
                            lastActivatedApplicationMenuItem.setEnabled(true);
                        }
                        lastActivatedApplicationMenuItem=menuItem;
                        menuItem.setEnabled(false);
                        MainFrame.this.activateApplication(app);
                    } catch (Exception ex) {
                        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            });
            if (conf.isDefaultApplication()) {
                lastActivatedApplicationMenuItem=menuItem;
                menuItem.setEnabled(false);
                this.activateApplication(app);
            }
        }
    }

    private void activateApplication(final Application application) throws Exception {
        if (serviceContext.getActiveApplication() != null) {
            serviceContext.getActiveApplication().closing();
            serviceContext.setActiveApplication(null);
        }
        serviceContext.setActiveApplication(application);
        

        this.taskQueue.addTask(new Task() {

            @Override
            public Object run() throws Exception {
                application.activated();

                SwingUtilities.invokeLater(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            context.reloadResources();
                        } catch (Exception ex) {
                            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        if (mainPanel.getComponentCount() != 0) {
                            mainPanel.remove(0);
                        }
                        
                        mainPanel.add(application.getMainView());
                        treeResources.updateUI();
                    }
                });
                return null;
            }
        });

    }
}
